package com.niit.spark.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * Date:2025/5/22
 * Author：Ys
 * Description:
 */
object StreamingWordCount01 {

  def main(args: Array[String]): Unit = {
    //环境准备
    val sparkConf = new SparkConf().setMaster("local[*]").setAppName("StreamingWordCount01")
    // --》初始化SparkStreaming环境
    val ssc = new StreamingContext(sparkConf, Seconds(3)) //Seconds(3) 采集周期，每隔3秒获取一次数据
    ssc.sparkContext.setLogLevel("ERROR")// 设置日志级别
    // --> 利用监听端号 套接字的方式创建DStream
    val lines: ReceiverInputDStream[String] = ssc.socketTextStream("localhost", 9999)// nc localhost 9999
   //---->例如，3秒分发送过来的数据是 “spark hello spark hello” ===>lines
   val word: DStream[String] = lines.flatMap(_.split(" "))
    //==> [spark,hello,spark,hello]
    val wordOne: DStream[(String, Int)] = word.map((_, 1))
    val wordCount: DStream[(String, Int)] = wordOne.reduceByKey(_ + _)

    //打印
    wordCount.print()

    //--> 开启采集器
    ssc.start()
    //--> 等待采集器的关闭
    ssc.awaitTermination()

  }

}
